package edu.worldskills.b;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String BASE_URL = "http://81.68.129.158/Module_A_2022/";

    List<Item> items ;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Button btn_my=findViewById(R.id.btn_my);
        btn_my.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(HomeActivity.this,MyActivity.class);
                startActivity(intent);
            }
        });

        showPictures();

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
// 定义动画持续时间
        final int ANIMATION_DURATION = 300;
        LinearLayout nav=findViewById(R.id.nav);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    // 滚动停止
                    case RecyclerView.SCROLL_STATE_IDLE:
//                        nav.setVisibility(View.VISIBLE);
                        // 显示导航栏，使用平移动画
                        nav.animate()
                                .translationY(0) // 平移回原始位置
                                .alpha(1.0f) // 透明度变为 1
                                .setDuration(ANIMATION_DURATION) // 动画持续时间
                                .withStartAction(() -> nav.setVisibility(View.VISIBLE)) // 动画开始时确保可见
                                .start();
                        break;

                    // 手指拖动或惯性滚动
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        // 隐藏导航栏，使用平移动画
                        // nav.setVisibility(View.GONE);
                        nav.animate()
                                .translationY(nav.getHeight()) // 平移到导航栏高度以下
                                .alpha(0.0f) // 透明度变为 0
                                .setDuration(ANIMATION_DURATION) // 动画持续时间
                                .withEndAction(() -> nav.setVisibility(View.GONE)) // 动画结束时设置为不可见
                                .start();
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });





        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 定义购物车按钮的引用
                LinearLayout nav=findViewById(R.id.nav);
                switch (newState) {
                    // 滚动停止
                    case RecyclerView.SCROLL_STATE_IDLE:
                        nav.setVisibility(View.VISIBLE);
                        break;
                    // 手指拖动
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        nav.setVisibility(View.GONE);
                        break;
                    // 惯性滚动
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        nav.setVisibility(View.GONE);
                        break;
                }
            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void showPictures() {

        items = new ArrayList<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(BASE_URL + "api/v1/goods");

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    try {
                        JSONObject jsonObject = new JSONObject(response.toString());
                        JSONArray spotsArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < spotsArray.length(); i++) {
                            JSONObject spot = spotsArray.getJSONObject(i);
                            String imageUrl = spot.getString("img_Url");
                            //此处需要获取图片的其他信息；
                            //String description = spot.getString("name");
                            Bitmap bitmap = downloadImage(imageUrl);
                            Item item=new Item(bitmap,"");
                            items.add(item);
                        }
                    } catch (JSONException e) {
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            RecyclerView recyclerView = findViewById(R.id.recyclerView);
                            CustomAdapter adapter = new CustomAdapter(items);
                            StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); // 2列，纵向
                            recyclerView.setLayoutManager(layoutManager);
                            recyclerView.setAdapter(adapter);

                        }
                    });

                } catch (IOException e) {
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    private Bitmap downloadImage(String imageUrl) {
        try {
            URL url = new URL(BASE_URL + imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(input);

            input.close();
            connection.disconnect();
            return bitmap;
        } catch (IOException e) {
            Log.e(TAG, "Error downloading image: " + e.getMessage());
            return null;
        }
    }
}

